package cn.sourcespro.shiro.service.impl;

import cn.sourcespro.shiro.crudparams.dto.AddUserDto;
import cn.sourcespro.shiro.dao.UserMapper;
import cn.sourcespro.shiro.entity.User;
import cn.sourcespro.shiro.service.UserService;
import cn.sourcespro.shiro.util.ShiroUtil;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/13
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public User findByUsername(String username) {
        return mapper.findByName(username);
    }

    @Override
    public void add(AddUserDto dto) {
        String password = dto.getPassword();
        String salt = ShiroUtil.generateSalt();
        String entryptPassword = ShiroUtil.entryptPassword(Sha256Hash.ALGORITHM_NAME, password, salt);

        User user = new User();
        user.setUsername(dto.getUsername());
        user.setNickname(dto.getNickname());
        user.setPassword(entryptPassword);
        user.setSalt(salt);
        user.setStatus((byte) 1);
        mapper.insert(user);
    }

    @Override
    public User findById(Long userId) {
        return mapper.selectByPrimaryKey(userId);
    }
}
